
import 'package:flutter/material.dart';
import 'package:flutter_base_app/base/base_page_view_model.dart';
import 'package:flutter_base_app/base/system_ui_styles.dart';
import 'package:provider/provider.dart';
import 'package:visibility_detector/visibility_detector.dart';

abstract class BasePageState<B extends BasePageViewModel, W extends StatefulWidget> extends State<W> {

  late final B viewModel;
  bool canPrintLog = true;
  late final AppLifecycleListener _listener;
  late Key visibilityKey;
  bool visible = false;

  void printLog(String text){
    if(canPrintLog){
      print(text);
    }
  }

  @override
  void initState() {
    super.initState();
    visibilityKey = Key('visibility_key_$this');
    viewModel = createViewModel();
    viewModel.initData();
    _listener = AppLifecycleListener(
      onShow: ()=> handleLifecycleTransition('show'),
      onResume: ()=> handleLifecycleTransition('resume'),
      onHide: ()=> handleLifecycleTransition('hide'),
      onInactive: ()=> handleLifecycleTransition('inactive'),
      onPause: ()=> handleLifecycleTransition('pause'),
      onDetach: ()=> handleLifecycleTransition('detach'),
      onRestart: ()=> handleLifecycleTransition('restart'),
      onStateChange: handleStateChange,
    );
  }

  B createViewModel();

  @override
  void dispose() {
    viewModel.destroy();
    _listener?.dispose();
    super.dispose();
  }

  void handleLifecycleTransition(String name) {
    printLog("$this -> handleLifecycleTransition $name");
  }

  void handleStateChange(AppLifecycleState state) {
    printLog("$this -> handleStateChange $state");
  }

  void onVisibilityChanged(VisibilityInfo info) {
    visible = info.visibleFraction == 1;
    printLog("$this -> onVisibilityChanged $visible");
  }


  @override
  Widget build(BuildContext context) {
    return SystemUIStyleCompat(
      value: systemUIDarkLight,
      child: ChangeNotifierProvider(
        create: (context) => viewModel,
        builder: (context, child) {
          //添加监听
          context.watch<B>();
          return buildPage(context);
        },
      ),
    );
  }

  Widget buildPage(BuildContext context){
    return VisibilityDetector(
      key: visibilityKey,
      onVisibilityChanged: onVisibilityChanged,
      child: Scaffold(
        backgroundColor: Colors.white,
        body: buildContent(context),
      ),
    );
  }

  Widget buildContent(BuildContext context);


}
